package it.rikesh.aip2011.client;


import java.util.List;
import java.util.logging.Logger;


import it.rikesh.aip2011.client.component.ActivityCategoryLayout;
import it.rikesh.aip2011.client.component.ActivityLayout;
import it.rikesh.aip2011.client.component.AddEditContentLayout;
import it.rikesh.aip2011.client.component.AreaLayout;
import it.rikesh.aip2011.client.component.FFaunaTypeLayout;
import it.rikesh.aip2011.client.component.FaunaFloraLayout;
import it.rikesh.aip2011.client.component.HomeLayout;
import it.rikesh.aip2011.client.component.HutLayout;
import it.rikesh.aip2011.client.component.TrailLayout;
import it.rikesh.aip2011.client.service.ActivityService;
import it.rikesh.aip2011.client.service.ActivityServiceAsync;
import it.rikesh.aip2011.client.service.FaunaFloraService;
import it.rikesh.aip2011.client.service.FaunaFloraServiceAsync;
import it.rikesh.aip2011.client.service.HutService;
import it.rikesh.aip2011.client.service.HutServiceAsync;
import it.rikesh.aip2011.client.service.TrailService;
import it.rikesh.aip2011.client.service.TrailServiceAsync;
import it.rikesh.aip2011.shared.model.Activity;
import it.rikesh.aip2011.shared.model.FaunaFlora;
import it.rikesh.aip2011.shared.model.Hut;
import it.rikesh.aip2011.shared.model.Trail;

import com.extjs.gxt.ui.client.Style.LayoutRegion;  
import com.extjs.gxt.ui.client.Style.Scroll;  
import com.extjs.gxt.ui.client.event.ButtonEvent; 
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;  
import com.extjs.gxt.ui.client.util.Margins;  
import com.extjs.gxt.ui.client.widget.ContentPanel; 
import com.extjs.gxt.ui.client.widget.LayoutContainer; 
import com.extjs.gxt.ui.client.widget.button.Button;  
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;  
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; 
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;  
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Classe che si occupa di definire la struttura del sito
 * 
 * @author  RN
 */
public class BaseLayout extends LayoutContainer {  
    private static final Logger log = Logger.getLogger(BaseLayout.class.getName());
    private final BorderLayout layout = new BorderLayout(); 
    private static HutServiceAsync hutService = GWT.create(HutService.class);
    private static ActivityServiceAsync activityService = GWT.create(ActivityService.class);
    private static TrailServiceAsync trailService = GWT.create(TrailService.class);
    private static FaunaFloraServiceAsync faunaService = GWT.create(FaunaFloraService.class);
    private static Menu menuSx=new Menu();
    private static MenuItem hutBtn; 
    private static MenuItem activityBtn;
    private static MenuItem activityByCategoryBtn;
    private static MenuItem trailBtn;
    private static MenuItem faunaBtn;
    private static MenuItem faunaByTypeBtn;
    private static Menu hutMenu = new Menu();
    private static Menu activityMenu = new Menu();
    private static Menu activityByCategoryMenu = new Menu();
    private static Menu trailMenu = new Menu();
    private static Menu faunaMenu = new Menu();
    private static Menu faunaByTypeMenu = new Menu();
    private static ContentPanel center = new ContentPanel();
    private static ContentPanel west = new ContentPanel();
    LayoutContainer home=new LayoutContainer();
    LayoutContainer who=new LayoutContainer();
    LayoutContainer hut=new LayoutContainer();
    LayoutContainer actyvity=new LayoutContainer();
    LayoutContainer trail=new LayoutContainer();
    LayoutContainer fauna=new LayoutContainer();
    
    /**
     * In questo metodo definirò i vari layout necessari
     * per visualizzare correttamente.
     * Mi occupero di inserire un HEADER, un 
     */
    protected void onRender(Element target, int index) {  
        super.onRender(target, index);  
        setLayout(layout);  
        setStyleAttribute("padding", "2%");  
        
        //Inizializzo i componenti del menu di sinistra
        hutBtn = new MenuItem("Rifugi");
        activityBtn = new MenuItem("Attività");
        activityByCategoryBtn = new MenuItem("Per categoria");
        trailBtn = new MenuItem("Sentieri");
        faunaBtn = new MenuItem("Fauna/Flora");  
        faunaByTypeBtn = new MenuItem("Per tipo");  
        
        //Definisco e inizializzo i vari panneli: North, Center, West
        ContentPanel north = new ContentPanel();  
        north.setHeaderVisible(false);
        north.setBorders(false);
        north.setBodyBorder(false);
        north.setHeight("250px");
        north.add(createMainMenu());

        north.setBodyStyle("background-image: url('images/head-1.jpg')");


        center.setBodyStyle("background-color: #F2F2F2");
        center.setBorders(false);
        center.setBodyBorder(false);
        center.setHeaderVisible(false);
        center.setScrollMode(Scroll.AUTOX);  
        center.setHeight(900);
        center.setWidth("100%");

        center.add(new HomeLayout());
        center.layout();
        
        
        
        west.setBodyStyle("background-color: #F2F2F2");
        west.setBorders(false);
        west.setBodyBorder(false);
        west.setHeaderVisible(false);
        west.setHeight(900);
        refreshMenu();

        

        BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 100);  
        northData.setCollapsible(true);  
        northData.setFloatable(true);  
        northData.setHideCollapseTool(true);  
        northData.setSplit(true);  
        northData.setMargins(new Margins(0, 0, 0, 0));  

        BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 150);  
        westData.setSplit(true);
        westData.setCollapsible(true);  
        westData.setMargins(new Margins(0,0,0,0));  

        BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
        centerData.setMargins(new Margins(0));  

        //Aggiungo i pannelli al container
        add(north, northData);  
        add(west, westData);  
        add(center, centerData); 
    }  

    /**
     * Metodo che si occupa di creare il menu a sinistra
     * responsabile della scelta dei vari topic
     * @return
     */
    private static Menu creaMenuSx(){ 
        //Questi sono i quattro pulsanti necessari
        //uno per i rifugi, uno per le attività, uno per i sentieri e uno per la flora flauna
        hutBtn.setStyleAttribute("width", "90px");
        activityBtn.setStyleAttribute("width", "90px");
        trailBtn.setStyleAttribute("width", "90px");
        faunaBtn.setStyleAttribute("width", "90px");
        
        /**
         * In questa parte definisco i vari listener per gestire i click nel menu di sinistra
         * Ad ogni click viene ricavato l'id dell'entità cosicchè si possa ricavare le informazioni
         */
        SelectionListener<MenuEvent> hutMnuListener = new SelectionListener<MenuEvent>() {  

            @Override  
            public void componentSelected(MenuEvent ce) {  
                String id = ce.getItem().getId().substring(ce.getItem().getId().lastIndexOf(":")+1, ce.getItem().getId().length()); 
                changeContent(new HutLayout(id));

            }  
        };
        SelectionListener<MenuEvent> activityMnuListener = new SelectionListener<MenuEvent>() {  

            @Override  
            public void componentSelected(MenuEvent ce) {  
                String id = ce.getItem().getId().substring(ce.getItem().getId().lastIndexOf(":")+1, ce.getItem().getId().length()); 
                if(id.equals("category")){
                    String app = ce.getItem().getId().substring(ce.getItem().getId().indexOf(":")+1, ce.getItem().getId().length()); 
                    String category = app.substring(0, app.lastIndexOf(":")); 
                    changeContent(new ActivityCategoryLayout(category));
                }
                else
                    changeContent(new ActivityLayout(id));  

            }  
        };
        SelectionListener<MenuEvent> trailMnuListener = new SelectionListener<MenuEvent>() {  

            @Override  
            public void componentSelected(MenuEvent ce) {  
                String id = ce.getItem().getId().substring(ce.getItem().getId().lastIndexOf(":")+1, ce.getItem().getId().length()); 
                changeContent(new TrailLayout(id));

            }  
        };
        SelectionListener<MenuEvent> faunaMnuListener = new SelectionListener<MenuEvent>() {  

            @Override  
            public void componentSelected(MenuEvent ce) {  
                String id = ce.getItem().getId().substring(ce.getItem().getId().lastIndexOf(":")+1, ce.getItem().getId().length()); 
                if(id.equals("type")){
                    String app = ce.getItem().getId().substring(ce.getItem().getId().indexOf(":")+1, ce.getItem().getId().length()); 
                    String type = app.substring(0, app.lastIndexOf(":")); 
                    changeContent(new FFaunaTypeLayout(type));
                }
                else
                    changeContent(new FaunaFloraLayout(id));

            }  
        };
//        final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
//            public void handleEvent(MessageBoxEvent ce) {  
//                Button btn = ce.getButtonClicked();  
//                Info.display("MessageBox", "The '{0}' button was pressed", btn.getText());  
//            }  
//        };  
//        SelectionListener<MenuEvent> sl4 = new SelectionListener<MenuEvent>() {  
//            public void componentSelected(MenuEvent ce) {  
//                MessageBox.alert("Alert", String.valueOf(ce.getMenu().getId()), l);  
//            }  
//        };  

        getHutList(hutMnuListener); 
        getActivityList(activityMnuListener);
        getTrailList(trailMnuListener);
        getFaunaList(faunaMnuListener);
        hutBtn.setSubMenu(hutMenu);  
        activityBtn.setSubMenu(activityMenu);
        trailBtn.setSubMenu(trailMenu);
        faunaBtn.setSubMenu(faunaMenu);
        menuSx.removeAll();
        menuSx.add(hutBtn);
        menuSx.add(activityBtn);
        menuSx.add(trailBtn);
        menuSx.add(faunaBtn);
        menuSx.setBorders(false);
        menuSx.setShadow(false);
        
        return menuSx;
    }

    /**
     * Metodo che si occupa di creare il menu principale. Associa i vari listener ai pulsanti
     * 
     * @return toolbar inizializzato
     */
    private ToolBar createMainMenu(){
        //Imposto il toolbar principale
        ToolBar toolBar = new ToolBar();

        SelectionListener<ButtonEvent> slHome = new SelectionListener<ButtonEvent>() {  

            @Override  
            public void componentSelected(ButtonEvent ce) {  
                changeContent(new HomeLayout());
            }  
        };
        SelectionListener<ButtonEvent> slWho = new SelectionListener<ButtonEvent>() {  

            @Override  
            public void componentSelected(ButtonEvent ce) {  
                changeContent(new AreaLayout());
            }  
        };
        SelectionListener<ButtonEvent> slAdmin = new SelectionListener<ButtonEvent>() {  

            @Override  
            public void componentSelected(ButtonEvent ce) {  
                  changeContent(new AddEditContentLayout());
            }  
        };

        //Inizializzo i vari bottoni e li inserisco in un toolbar
        Button item1 = new Button("Home",slHome);  
        toolBar.add(item1);  
        toolBar.add(new SeparatorToolItem());  
        Button splitItem = new Button("Dove siamo",slWho);   
        toolBar.add(splitItem);  
        toolBar.add(new SeparatorToolItem());  
        Button toggle = new Button("Admin",slAdmin);  
        toolBar.add(toggle);  
        toolBar.add(new SeparatorToolItem());  
        toolBar.setHeight("18px");
        toolBar.setDeferHeight(true);
        toolBar.setAutoHeight(true);
        //      toolBar.setAlignment(HorizontalAlignment.RIGHT);
        toolBar.setPosition(0, 76);
        return toolBar;
    }
    
    /**
     * Metodo che permette di recuperare tutti gli hut dal datastore
     * @param hutBtnListener listener del tasto
     */
    public static void getHutList(final SelectionListener<MenuEvent> hutBtnListener){
        hutService.getHutList(new AsyncCallback<List<Hut>>() {
            
            public void onSuccess(List<Hut> result) {
                for (Hut hut : result) {
                    MenuItem menu=new MenuItem(hut.getName(),hutBtnListener);
                    menu.setId("hutmnu:"+String.valueOf(hut.getKey().getId()));
                    hutMenu.add(menu);
                }
                
            }
            
            public void onFailure(Throwable caught) {
                
            }
        });
        
        
    }
    
    /**
     * Metodo che permette di recuperare tutti gli activity dal datastore
     * @param hutBtnListener listener del tasto
     */
    public static void getActivityList(final SelectionListener<MenuEvent> activityBtnListener){
        activityService.getActivityList(new AsyncCallback<List<Activity>>() {
            
            public void onSuccess(List<Activity> result) {
                activityMenu.removeAll();
                for (Activity activity : result) {
                    MenuItem menu = new MenuItem(activity.getName(),activityBtnListener);
                    menu.setId("activitymnu:"+String.valueOf(activity.getKey().getId()));
                    activityMenu.add(menu);
                }
                MenuItem menu = new MenuItem("Sci",activityBtnListener);
                menu.setId("activitymnu:Sci:category");
                activityByCategoryMenu.add(menu);
                MenuItem menu2 = new MenuItem("Alpinismo",activityBtnListener);
                menu2.setId("activitymnu:Alpinismo:category");
                activityByCategoryMenu.add(menu2);
                activityByCategoryBtn.setSubMenu(activityByCategoryMenu);
                activityMenu.add(activityByCategoryBtn);
                
            }
            
            public void onFailure(Throwable caught) {
                
            }
        });
    }
    
    /**
     * Metodo che permette di recuperare tutti i trail dal datastore
     * @param hutBtnListener listener del tasto
     */
    public static void getTrailList(final SelectionListener<MenuEvent> trailBtnListener){
        trailService.getTrailList(new AsyncCallback<List<Trail>>() {
            
            public void onSuccess(List<Trail> result) {
                for (Trail trail : result) {
                    MenuItem menu = new MenuItem(trail.getName(),trailBtnListener);
                    menu.setId("trailmnu:"+String.valueOf(trail.getKey().getId()));
                    trailMenu.add(menu);
                }
                
            }
            
            public void onFailure(Throwable caught) {
                
            }
        });
    }
    
    /**
     * Metodo che permette di recuperare tutta la fauna e la flora dal datastore
     * @param hutBtnListener listener del tasto
     */
    public static void getFaunaList(final SelectionListener<MenuEvent> faunaBtnListener){
        faunaService.getFaunaList(new AsyncCallback<List<FaunaFlora>>() {
            
            public void onSuccess(List<FaunaFlora> result) {
                log.info("result: "+result);
                faunaMenu.removeAll();
                for (FaunaFlora fauna : result) {
                    MenuItem menu = new MenuItem(fauna.getName(),faunaBtnListener);
                    menu.setId("faunamnu:"+String.valueOf(fauna.getKey().getId()));
                    faunaMenu.add(menu);
                }
                MenuItem menu = new MenuItem("Fauna",faunaBtnListener);
                menu.setId("activitymnu:Fauna:type");
                faunaByTypeMenu.add(menu);
                MenuItem menu2 = new MenuItem("Flora",faunaBtnListener);
                menu2.setId("activitymnu:floratype");
                faunaByTypeMenu.add(menu2);
                faunaByTypeBtn.setSubMenu(faunaByTypeMenu);
                faunaMenu.add(faunaByTypeBtn);
                
            }
            
            public void onFailure(Throwable caught) {
                
            }
        });
    }
    
    
    /**
     * Questo metodo si occupa di visualizzare uno specifico layout
     * @param layout layout da visualizzare, es. HutLayout
     */
    public static void changeContent(LayoutContainer layout){
        center.removeAll();
        center.add(layout);
        center.layout();
    }
    
    /**
     * Questo metodo si occupa di aggirnare il menù a sinistra.
     * Viene chiamato quando il contenuto del menù viene modificato
     */
    public static void refreshMenu(){
        west.removeAll();
        west.add(creaMenuSx());
        west.layout();
            
    }
}  